//
//  BMSPrivacyExitView.m
//  WDBMS
//
//  Created by YeJary on 2025/5/12.
//

#import "BMSPrivacyExitView.h"
#import <Masonry/Masonry.h>
#import "BMSPopupQueueManager.h"
#import "BMSRealnamePopupView.h"
#import <SafariServices/SafariServices.h>
#import "BMSPrivate.h"
#import "BMSInitializer.h"
#import "BMSLinkOpener.h"
#import "BMSAppInfoHelper.h"

@interface BMSPrivacyExitView()<UITextViewDelegate>


@end

@implementation BMSPrivacyExitView {
    UIView *_contentView;
    UILabel *_titleLabel;
    UITextView *_textView;
    UIButton *_agreeBtn;
    UIButton *_disagreeBtn;
    UIView *_maskView;
}

- (instancetype)init {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    self.userInteractionEnabled = YES;
    if (self) {
        [self setupViews];
    }
    return self;
}

- (void)setupViews {
    // 弹窗容器
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = UIColor.whiteColor;
    _contentView.layer.cornerRadius = 12;
    _contentView.clipsToBounds = YES;
    [self addSubview:_contentView];

    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.greaterThanOrEqualTo(@280);
        make.width.lessThanOrEqualTo(self).multipliedBy(0.85);
        make.width.lessThanOrEqualTo(@400);
        make.height.lessThanOrEqualTo(self.mas_height).multipliedBy(0.95);
    }];

    // 标题
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.text = @"用户协议和隐私政策";
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [_contentView addSubview:_titleLabel];

    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_contentView.mas_top).offset(20);
        make.left.right.equalTo(_contentView).insets(UIEdgeInsetsMake(0, 16, 0, 16));
        make.height.mas_equalTo(24);
    }];

    // 富文本正文
    _textView = [[UITextView alloc] init];
    _textView.editable = NO;
    _textView.scrollEnabled = YES;
    _textView.textContainerInset = UIEdgeInsetsZero;
    _textView.textContainer.lineFragmentPadding = 0;
    _textView.delegate = self;
    [_contentView addSubview:_textView];

    NSString *text = @"为了您的个人信息安全，如不同意《用户协议》和《隐私政策》，很遗憾我们将无法为您提供服务。如需继续使用，请点击“同意”开始游戏。";
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 4;

    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:@{
        NSFontAttributeName: [UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName: UIColor.blackColor,
        NSParagraphStyleAttributeName: style
    }];
    
    NSString *termUrl = [BMSInitializer shared].launchModel.termUrl.length > 0
                        ? [BMSInitializer shared].launchModel.termUrl
                        : [BMSAppInfoHelper BMSJSONFileFromtermUrl];
    
    NSString *privacyUrl = [BMSInitializer shared].launchModel.privacyUrl.length > 0 ? [BMSInitializer shared].launchModel.privacyUrl : [BMSAppInfoHelper BMSJSONFileFromPrivacyUrl];

    [attrStr addAttribute:NSLinkAttributeName value:termUrl range:[text rangeOfString:@"《用户协议》"]];
    [attrStr addAttribute:NSLinkAttributeName value:privacyUrl range:[text rangeOfString:@"《隐私政策》"]];
    _textView.attributedText = attrStr;

    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleLabel.mas_bottom).offset(12);
        make.left.right.equalTo(_contentView).insets(UIEdgeInsetsMake(0, 16, 0, 16));
        make.height.greaterThanOrEqualTo(@80);
        make.height.lessThanOrEqualTo(@160);
    }];

    // 退出按钮
    _disagreeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_disagreeBtn setTitle:@"退出" forState:UIControlStateNormal];
    _disagreeBtn.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    [_disagreeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _disagreeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    _disagreeBtn.layer.cornerRadius = 6;
    [_disagreeBtn addTarget:self action:@selector(onDisagree) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_disagreeBtn];

    // 同意按钮
    _agreeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_agreeBtn setTitle:@"同意" forState:UIControlStateNormal];
    _agreeBtn.backgroundColor = UIColor.systemBlueColor;
    [_agreeBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    _agreeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    _agreeBtn.layer.cornerRadius = 6;
    [_agreeBtn addTarget:self action:@selector(onAgree) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_agreeBtn];

    [_disagreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_textView.mas_bottom).offset(20);
        make.left.equalTo(_contentView.mas_left).offset(16);
        make.height.mas_equalTo(44);
        make.bottom.equalTo(_contentView.mas_bottom).offset(-16);
    }];

    [_agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.equalTo(_disagreeBtn);
        make.left.equalTo(_disagreeBtn.mas_right).offset(12);
        make.right.equalTo(_contentView.mas_right).offset(-16);
        make.width.equalTo(_disagreeBtn);
    }];
}

#pragma mark - Interaction

- (void)onAgree {
    [NSUserDefaults.standardUserDefaults setBool:YES forKey:kBMSKeyPrivacyAgreed];

    if (self.completion) {
        BOOL agreed = YES;
        [[BMSPopupQueueManager sharedManager] dismissCurrentPopupWithCompletion:^{
            self.completion(agreed);
            // 等上一个弹窗完全关闭后再弹
        }];
    } else {
        [[BMSPopupQueueManager sharedManager] dismissCurrentPopup];
    }
}

- (void)onDisagree {
    [self dismiss];
    [NSUserDefaults.standardUserDefaults setBool:NO forKey:kBMSKeyPrivacyAgreed];
    if (self.completion) self.completion(NO);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            exit(0); // 强制退出应用（用户不同意隐私协议）
        });
}

#pragma mark - Show / Dismiss

- (void)showWithCompletion:(BMSPrivacyDecisionHandler)completion {
//    BMSPrivacyPopupView *popup = [[BMSPrivacyPopupView alloc] init];
    
}

- (void)dismiss {
//    BMSPrivacyPopupView *popup = [[BMSPrivacyPopupView alloc] init];
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView
shouldInteractWithURL:(NSURL *)URL
         inRange:(NSRange)characterRange
     interaction:(UITextItemInteraction)interaction
{
    if ([URL.absoluteString containsString:@"http://"] ||
        [URL.absoluteString containsString:@"https://"]) {

        [BMSLinkOpener openURL:URL.absoluteString];
        NSLog(@"跳转链接：%@", URL);
        return NO; // ✅ 阻止系统默认行为（跳 Safari）
    }

    return NO;
}

#pragma mark --------- safariServices ------------

- (void)openProtocolURL:(id)urlObject from:(UIViewController *)vc {
    if ([urlObject isKindOfClass:[NSString class]]) {
        urlObject = [NSURL URLWithString:(NSString *)urlObject];
    }
    if (![urlObject isKindOfClass:[NSURL class]]) {
        NSLog(@"[BMS] 无效协议链接类型: %@", urlObject);
        return;
    }

    NSURL *url = (NSURL *)urlObject;
    if (!url || !url.scheme || ![url.scheme hasPrefix:@"http"]) {
        NSLog(@"[BMS] URL 无效或不支持: %@", url);
        return;
    }

    SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:url];
    safariVC.modalPresentationStyle = UIModalPresentationPageSheet;
    [vc presentViewController:safariVC animated:YES completion:nil];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
